import React, { useState, useEffect } from 'react';
import { Row, Col, Card, Button, Empty, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { TodoService } from '../services/todoService';
import TodoItem from './TodoItem';
import TodoForm from './TodoForm';
import dayjs from 'dayjs';
import AchievementModal from './AchievementModal';

function TodoList({ theme, selectedDate, todos, setTodos }) {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingTodo, setEditingTodo] = useState(null);
  const [loading, setLoading] = useState(false);
  const [showAchievement, setShowAchievement] = useState(false);

  useEffect(() => {
    if (selectedDate && todos.length > 0) {
      checkAchievement(todos);
    }
  }, [selectedDate, todos]);

  const fetchTodos = async () => {
    try {
      setLoading(true);
      const data = await TodoService.getAllTodos();
      console.log('后端返回的数据:', data);
      if (Array.isArray(data) && data.length > 0) {
        setTodos(data);
      }
    } catch (error) {
      console.error('获取待办事项失败:', error);
      message.error('获取待办事项失败');
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    fetchTodos();
  }, [setTodos]);

  const handleAddTodo = async (values) => {
    try {
      await TodoService.addTodo(values);
      message.success('添加成功');
      setIsModalVisible(false);
      fetchTodos();
    } catch (error) {
      message.error('添加失败');
    }
  };

  const handleUpdateTodo = async (values) => {
    try {
      await TodoService.updateTodo(values);
      message.success('更新成功');
      setIsModalVisible(false);
      setEditingTodo(null);
      const data = await TodoService.getAllTodos();
      if (Array.isArray(data) && data.length > 0) {
        setTodos(data);
        checkAchievement(data);
      }
    } catch (error) {
      message.error('更新失败');
    }
  };

  const handleDeleteTodo = async (id) => {
    try {
      if (!id) {
        message.error('无效的待办事项ID');
        return;
      }
      await TodoService.deleteTodo(id);
      message.success('删除成功');
      fetchTodos();
    } catch (error) {
      console.error('删除失败:', error);
      message.error('删除失败');
    }
  };

  const filteredTodos = selectedDate
    ? todos.filter(todo => dayjs(todo.deadTime).format('YYYY-MM-DD') === selectedDate)
    : todos;

  const checkAchievement = (updatedTodos) => {
    if (selectedDate) {
      const todosForDate = updatedTodos.filter(
        todo => dayjs(todo.deadTime).format('YYYY-MM-DD') === selectedDate
      );
      const allCompleted = todosForDate.length > 0 && 
        todosForDate.every(todo => todo.isCompleted);
      
      if (allCompleted) {
        setShowAchievement(true);
      }
    }
  };

  return (
    <>
      <Row gutter={[16, 16]}>
        <Col xs={24}>
          <Card
            style={{
              background: theme.colorBgContainer,
              boxShadow: theme.boxShadow,
            }}
          >
            <Button
              type="primary"
              icon={<PlusOutlined />}
              onClick={() => setIsModalVisible(true)}
              style={{ width: '100%', height: '50px', fontSize: '16px' }}
            >
              添加新待办事项
            </Button>
          </Card>
        </Col>
        {(!filteredTodos || filteredTodos.length === 0) && !loading ? (
          <Col xs={24}>
            <Empty description={selectedDate ? `${dayjs(selectedDate).format('MM月DD日')}暂无待办事项` : "暂无待办事项"} />
          </Col>
        ) : (
          Array.isArray(filteredTodos) && 
          filteredTodos.map((todo) => (
            <Col xs={24} sm={12} lg={8} key={todo.id}>
              <TodoItem
                todo={todo}
                onEdit={(todo) => {
                  setEditingTodo(todo);
                  setIsModalVisible(true);
                }}
                onDelete={handleDeleteTodo}
                onStatusChange={handleUpdateTodo}
                theme={theme}
              />
            </Col>
          ))
        )}
      </Row>

      <TodoForm
        visible={isModalVisible}
        onCancel={() => {
          setIsModalVisible(false);
          setEditingTodo(null);
        }}
        onSubmit={editingTodo ? handleUpdateTodo : handleAddTodo}
        initialValues={editingTodo}
        theme={theme}
      />

      <AchievementModal
        visible={showAchievement}
        onClose={() => setShowAchievement(false)}
      />
    </>
  );
}

export default TodoList; 